import 'package:flutter/material.dart';
import 'package:flutter_app_update/azhon_app_update.dart';
import 'package:flutter_app_update/update_model.dart';
import 'package:flutter_project/common/update/update_version_controller.dart';
import 'package:get/get.dart';


import '../../../config/theme_color.dart';
import '../utils/screen_size_utils.dart';

class UpdateVersionPage extends StatefulWidget {
  String content = '优化已知问题';
  int update = 1;
  Function? refuseAction;

  UpdateVersionPage(
      {this.content = '优化已知问题', this.update = 1, this.refuseAction, super.key});

  @override
  State<UpdateVersionPage> createState() => _UpdateVersionPageState();
}

class _UpdateVersionPageState extends State<UpdateVersionPage> {
  UpdateVersionController bindController = Get.put(UpdateVersionController());
  double outerMargin = 40.0;
  double innerSpace = 20.0;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color: Colors.white,
        ),
        margin: EdgeInsets.symmetric(horizontal: outerMargin),
        height: ScreenSizeUtils.deviceScreenWidth(context) -
            outerMargin * 2 -
            innerSpace * 2,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(
              height: 33,
            ),
            const Center(
              child: Text(
                '发现新版本',
                style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
              ),
            ),
            const SizedBox(height: 20),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: innerSpace),
                      child: Text(widget.content),
                    ),
                  ],
                ),
              ),
            ),
            const SizedBox(
              height: 10,
            ),
            GetBuilder(
                id: bindController.progressViewId,
                builder: (UpdateVersionController controller) {
                  return Offstage(
                    offstage: controller.isHidden,
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 20),
                      child: Column(
                        children: [
                          Stack(
                            children: [
                              Container(
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(5),
                                  color: ThemeColor.sendMsgColor,
                                ),
                                height: 10,
                              ),
                              Container(
                                margin: const EdgeInsets.only(top: 1),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(5),
                                  color: ThemeColor.mainColor,
                                ),
                                width: controller.rateWidth,
                                height: 8,
                              ),
                            ],
                          ),
                          Text(
                            '${controller.ratePercent}%',
                            style: TextStyle(color: ThemeColor.mainColor),
                          ),
                        ],
                      ),
                    ),
                  );
                }),
            GetBuilder(
                id: bindController.bottomBtnViewId,
                builder: (UpdateVersionController controller) {
                  return Visibility(
                    visible: controller.isHidden,
                    child: widget.update == 2
                        ? Container(
                            margin: const EdgeInsets.symmetric(horizontal: 20),
                            padding: const EdgeInsets.symmetric(vertical: 10),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: ThemeColor.mainColor,
                                borderRadius: BorderRadius.circular(10)),
                            child: const Text(
                              '立即更新',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold),
                            ),
                          )
                        : Row(
                            children: [
                              Expanded(
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        controller.isHidden = false;
                                        controller.update([
                                          controller.bottomBtnViewId,
                                          controller.progressViewId
                                        ]);
                                        _appUpdate();
                                      },
                                      child: Text(
                                        '立即更新',
                                        style: TextStyle(
                                            color: ThemeColor.mainColor,
                                            fontWeight: FontWeight.bold),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(
                                width: 10,
                              ),
                              Expanded(
                                child: Row(
                                  //mainAxisSize: MainAxisSize.min,
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: [
                                    GestureDetector(
                                      onTap: () {
                                        Navigator.of(context).pop();
                                        if(widget.refuseAction!=null){
                                          widget.refuseAction!();
                                        }
                                      },
                                      child: Text(
                                        '残忍拒绝',
                                        style: TextStyle(
                                            color: ThemeColor.checkNormalColor),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                  );
                }),
            const SizedBox(
              height: 18,
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    AzhonAppUpdate.listener((map) {
      Map resMap = map;
      if (map['type'] == 'downloading') {
        if (resMap.keys.contains('max')) {
          int max = map['max'];
          int progress = map['progress'];
          double rate = progress / max;
          String rateStr = rate.toStringAsFixed(2);
          double ratePer = double.parse(rateStr) * 100;
          bindController.ratePercent = ratePer.toInt();
          bindController.rateWidth = rate *
              (ScreenSizeUtils.deviceScreenWidth(context) -
                  outerMargin * 2 -
                  innerSpace * 2);
          bindController.update([bindController.progressViewId]);
        }
      }
    });
  }

  _appUpdate() {
    String url =
        "https://reelplay.tos-cn-beijing.volces.com/reelfree-test/app-release.apk";
    UpdateModel model = UpdateModel(url, "app-release.apk", "ic_launcher",
        'https://itunes.apple.com/cn/app/抖音/id1142110895',
        showBgdToast: false);
    AzhonAppUpdate.update(model).then((value) => debugPrint('$value'));
  }
}
